﻿using AyFrame.NSerialLog;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AyFrame.WebApi.Filters
{
    public class LogAttribute : ControllerAttribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //throw new NotImplementedException();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var data = context.RouteData;

            var controller = context.Controller.GetType().Name;
            var action = data.Values["Action"].ToString();
            var method = context.HttpContext.Request.Method;

            string dataStr;
            if (method.ToUpper() == "POST")
                dataStr = context.ActionArguments.Values.Select(t => JsonConvert.SerializeObject(t)).Aggregate("", (a, b) => a += $"{b};");
            else
                dataStr = data.Values.Where(t => t.Key != "Controller" && t.Key != "Actoin").ToList().Aggregate("", (a, b) => a += $"{b};");

            //var dataStr = JsonConvert.SerializeObject(metaData);
            dataStr = $"【{method}】{controller.Replace("Controller", "")}/{action}\r\n data==> {dataStr}";

            LogHelper.LogInfo(dataStr);

        }
    }
}
